Skip to content

Add Streamable HTTP transport and per-server headers for MCP servers (part of #185) - #541

Open
rohantiwari9573 wants to merge 3 commits into
CraftOS-dev:devfrom
rohantiwari9573:feat/issue-185-streamable-http
Open

rohantiwari9573 wants to merge 3 commits into
CraftOS-dev:devfrom
rohantiwari9573:feat/issue-185-streamable-http

Conversation

@rohantiwari9573

@rohantiwari9573 rohantiwari9573 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Depends on #540 (this branch is stacked on it; review the top commit only until #540 is merged).
Part of #185.

Summary

This adds the MCP Streamable HTTP transport ("transport": "http") with per-server HTTP headers and a per-server request timeout. It covers configuration in mcp_config.json, the /mcp command, profile bundles and AGENT.md.

  • Several remote and local servers can run side by side.
  • Each server gets its own headers and credentials.
  • The existing settings UIs keep working unchanged.
  • The UI changes (write-only secrets and a form editor) are in a follow-up PR.

The transport is written directly on httpx, which is already a dependency. No new dependencies are added. It is tested against the official MCP Python SDK server (see Testing).

Streamable HTTP behaviour (spec 2025-03-26 … 2025-11-25)

  • Requests: JSON-RPC requests are POSTed with Accept: application/json, text/event-stream. Both plain JSON and SSE-stream responses are handled. Notifications expect 202 Accepted.
  • Protocol versions: the client requests 2025-11-25, and accepts 2025-03-26, 2025-06-18 or 2025-11-25 from the server. Anything else fails the connection with a clear error. The negotiated version is sent as MCP-Protocol-Version on later requests.
  • Sessions: the Mcp-Session-Id returned by initialize is sent on every later request.
    • If a request that carried a session gets 404, the session is renewed once (re-initialize) and the request is retried once.
    • Concurrent requests share a single renewal.
  • Resumption: if an SSE stream closes before its response arrives, it is resumed with GET + Last-Event-ID. This happens at most 2 times, within the request's deadline, and honours the server's retry.
  • Server requests during a stream: ping is answered; any other request gets -32601.
  • Close: sends DELETE with the session id (5 s limit), then closes the client.
  • No redirects: redirects are not followed, so headers and credentials only go to the configured URL.
  • Limits:
    • each message is capped at 16 MB (larger responses are rejected without being buffered);
    • error bodies are read up to 64 KB, and server text in errors and logs is limited to 300 printable characters;
    • tool listing follows nextCursor for up to 50 pages.

Configuration

{
  "mcp_servers": [
    {
      "name": "stitch",
      "description": "Remote MCP server over Streamable HTTP",
      "transport": "http",
      "url": "https://example.com/mcp",
      "headers": { "X-Api-Key": "${STITCH_API_KEY}" },
      "env": { "STITCH_API_KEY": "" },
      "timeout": 30,
      "enabled": true
    }
  ]
}
  • Transport names: streamable_http and streamable-http are accepted as aliases and saved as http.
  • url: must be http:// or https://, with a host. User info (user:pass@), fragments and spaces are rejected.
  • headers:
    • names must be RFC 9110 tokens;
    • values cannot contain control characters (no CR/LF header splitting);
    • names are case-insensitive, so duplicates are rejected;
    • headers the transport sets itself cannot be configured (Accept, Content-Type, Host, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID and the hop-by-hop headers).
  • timeout: seconds per request, 0 < timeout ≤ 300, default 30. A tool handler waits timeout + 10 seconds, minimum 60, so the transport's own timeout fires first.

${NAME} resolution rule

${NAME} in a header value is read only from that server's own env, never from the process environment. A missing or empty value fails that server with "set NAME in this server's env" rather than sending an empty credential. This means a config entry written by the agent, or one imported in a profile bundle, cannot pull arbitrary environment variables (other servers' keys, cloud credentials) into a request to its own URL.

Lifecycle and reload

  • Servers connect concurrently, and one failing server doesn't affect the others. Failed servers appear in status with their error.
  • reload():
    • reconnects a server only when its connection settings changed (by fingerprint) or its connection is down;
    • disconnects removed servers and unregisters exactly the actions they registered;
    • keeps a server whose new entry is invalid running on its last good settings, and reports the error.
  • Invalid entries: entries that fail validation (including duplicate names) are kept in the file on save and reported. Before, they were skipped with a log warning and dropped on the next save.
  • Cancellation: cancelling during connect disconnects cleanly. Shutdown disconnects all servers concurrently.
  • Logging: URLs are logged with credentials and query strings redacted. Header values are never logged.

/mcp, settings and profile bundles

  • /mcp add <name> --transport http <url> [--timeout N]
  • /mcp header <name> <Header> <value> and /mcp header <name> <Header> --remove
  • /mcp list shows the transport, env keys that still need a value, and invalid entries.
  • Fix: /mcp add <name> --transport stdio -- python server.py now splits the command from its arguments.
  • Settings payload: keeps today's shape for the existing browser and terminal editors. Header values and stdio arguments are not sent; headers are listed by name, with the env keys they use.
  • Profile bundles:
    • entries are validated with the same rules as mcp_config.json;
    • literal header values are blanked on export, while ${NAME} templates are kept;
    • on import, local credentials are preserved only when the entry points to the same server (same transport and URL or command).
  • AGENT.md (both copies) documents the http transport, headers, timeout and /mcp header.

Testing

All runs are on Windows 11, Python 3.10 unless noted, from a clean checkout of this branch.

Check Result
test_mcp_config.py 67 passed
test_mcp_streamable_http.py (local mock server) 42 passed
test_mcp_client_lifecycle.py 12 passed
test_mcp_settings.py 31 passed
test_mcp_adapter_names.py (from #540) 5 passed
test_mcp_streamable_http_interop.py against the official mcp 2.3.0 SDK server: connect, list and call in JSON and SSE modes, stateful and stateless (4); a wrong API key is refused (1); the SDK is really present (1) 6 passed
All tests/test_mcp*.py, with interop enabled 206 passed, 8 skipped (POSIX-only stdio cases)
Same on Python 3.14 206 passed, 8 skipped
Full suite (pytest --continue-on-collection-errors --assert=plain, 9 min 36 s) 5081 passed, 46 skipped, 19 deselected (live), 5 failed, 1 collection error; all 6 also fail on dev without this change (see below)
ruff check and ruff format clean
mypy no new errors (117, down from 126 on dev)
  • Interop test: opt-in. Point CRAFTBOT_MCP_INTEROP_PYTHON at an interpreter that has mcp 2.x installed. It is skipped otherwise.
  • Python 3.14: the run imports agent_core.core.impl.action.manager before pytest, as the app does at startup. Without that, the existing nest_asyncio issue on 3.14 also makes dev's own SSE tests fail.
  • --assert=plain: used for the full-suite runs. In a CRLF checkout, pytest's detailed assertion diff for the known AGENT.md failure takes many minutes; plain asserts run every test unchanged and skip only that diff.
  • Known failures on dev:
    • test_agent_md_copies_identical_and_mention_mini_browser;
    • four test_process_ledger port tests ("listener … never came up");
    • a collection error in test_web_search_cse_base_url.py (missing googleapiclient).
  • Not tested:
    • no live remote endpoint, including Stitch: only the mock server and the SDK server were used;
    • no CI runs these tests.

Limits and behaviour changes

  • ${NAME} no longer falls back to the process environment. This applies to http headers, which are new, so no existing config relies on it.
  • Duplicate server names are now reported as invalid entries. Before, both were loaded and lookups by name used the first one.
  • Not implemented: OAuth authorization flows, and a standalone GET listener for unsolicited server messages. Headers cover API-key and bearer-token servers.
  • Existing installs keep their current agent_file_system/AGENT.md. The template copy carries the new docs.

Size

The diff is +4024/−236 across 18 files. About 2,280 lines are new tests, and about 1,740 are production code and docs. I kept it as one PR because the transport, the config validation and the reload logic share the same header and env rules. If it's easier to review, I can split it into:

  1. config and transport with their tests;
  2. lifecycle, /mcp, settings and bundles.

rohantiwari9573 and others added 2 commits November 23, 2026 17:56
MCP tool names are chosen by the MCP server and can contain any
character, including quotes, backslashes and newlines. Build the
generated handler source with repr() literals, so every server and
tool name is kept exactly as a string, in the docstring as well as in
the values the handler uses. Action names and calls are unchanged.

Adds tests with names containing quotes, newlines, triple quotes and a
line continuation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… for MCP

Adds the MCP Streamable HTTP transport ("transport": "http", with the
aliases streamable_http and streamable-http): JSON and SSE responses,
Mcp-Session-Id and MCP-Protocol-Version handling, renewing an expired
session once, resuming SSE streams, a size limit per message and
DELETE on close. Redirects are not followed.

Per-server "headers" and "timeout" are validated in mcp_config.json.
${NAME} references in header values resolve only from that server's
own "env", never from the process environment. Header values are
never listed or logged, and URLs are logged without credentials.

Also:
- reload reconnects changed or dead servers and keeps the last good
  settings of a server whose new entry is invalid;
- invalid entries are kept on save and reported;
- tool listing is paginated;
- /mcp add --transport http and /mcp header;
- profile bundles validate entries with the same rules and keep local
  credentials only for the same server;
- AGENT.md documents the http transport.

The settings payload for the existing editors is unchanged; header
values and stdio arguments are not sent.

Part of CraftOS-dev#185.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@zfoong zfoong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. On my side all the MCP tests pass (Linux, Python 3.10), including the interop tests against the official mcp 2.3.0 SDK server. A few things I'd like fixed before merging:

1. SSE data is split on Unicode line separators (agent_core/core/impl/mcp/server.py:1353)
stream.aiter_lines() uses httpx's line decoder, which splits like str.splitlines() (U+2028, U+2029, U+0085, \x0b, \x0c, \x1c–\x1e), not only on CR/LF as SSE requires. Both official SDKs write U+2028/U+0085 raw inside data:. A tool result containing one (scraped web text, for example) gets cut in half, the JSON parse fails, and the call ends with "response stream ... ended before the response arrived". Splitting the byte stream on \r\n|\r|\n yourself fixes it. The existing SSETransport (line 590) has the same issue, if you want to fix both.

2. The 16 MB cap doesn't bound memory on SSE (server.py:1380-1399)
The size check runs only after httpx has buffered a whole line, so a data line with no newline is buffered without limit until the deadline. A single 200 MB line peaked at about 830 MB RSS before the "exceeds the 16 MB" error. The byte-level splitter from #1, with a size cap, covers this too.

3. Existing configs become invalid after upgrade (agent_core/core/impl/mcp/config.py:200 and :259)
On dev these entries load and connect (the extra keys are ignored). On this branch they're rejected and the server stops connecting:

{"name": "a", "transport": "stdio", "command": "npx", "args": ["x"], "timeout": 60000}
{"name": "b", "transport": "sse", "url": "https://h/sse", "headers": {"Authorization": "Bearer t"}}

Could you validate timeout and headers only for http, or warn and ignore them for the other transports?

4. Bundle import silently drops local credentials (app/ui_layer/settings/profile_bundle.py:841-862)
In replace mode, if a same-named server's command, args or URL differ even slightly (a version pin, a path, a trailing slash), the local entry is replaced with the bundle's blank env and the user's saved tokens are gone, with only a log warning. I agree with the security reasoning, but please either keep the local entry or report it in the import result.

Minor

  • Session renewal never clears the old Mcp-Session-Id (server.py:1068-1075, :1154). If the new initialize response has no session id (for example, the server restarted as stateless), the stale id goes out with notifications/initialized, gets a 404, and the server stays disconnected until a reload or restart.

…dentials

- Split SSE streams on CR, LF and CRLF only. httpx's aiter_lines also
  splits on U+2028, U+0085 and the other str.splitlines separators,
  which servers send unescaped inside JSON data. Both the Streamable
  HTTP transport and the legacy SSE transport use the new splitter.
- Enforce the 16 MB limit while a line is being read, so an
  unterminated line is never held in memory in full.
- Accept "headers" and "timeout" on stdio, sse and websocket entries
  again, as earlier versions did. They are ignored with a one-time
  warning and kept unchanged in the file.
- Profile bundle import keeps a local entry that has saved credentials
  when the bundle's entry with the same name reaches a different
  server, and reports the name as skipped.
- Clear the old Mcp-Session-Id when a renewed session comes back
  without one.
- Never save over an MCP config file that exists but cannot be read
  when adding a server; report the error instead.

Part of CraftOS-dev#185.
rohantiwari9573 added a commit to rohantiwari9573/CraftBot that referenced this pull request Nov 25, 2026
@rohantiwari9573

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All five points are fixed in 61709e2:

  1. Unicode line separators: SSE streams are now split on CR, LF and CRLF only, using a byte-level splitter, in both the Streamable HTTP transport and the legacy SSETransport. New tests send U+2028, U+2029 and U+0085 unescaped inside data:, and cover line endings split across chunks.
  2. Memory bound: the 16 MB limit is checked while a line is being read. With an unterminated 200 MB line, peak Python memory is now 16.9 MB (601 MB before).
  3. Old configs: headers and timeout on stdio, sse and websocket entries load again. They're ignored with a one-time warning and kept unchanged in the file, so switching an entry to http applies them. Your two example entries are in the tests.
  4. Bundle import: when the bundle's entry reaches a different server and the local entry has saved credentials, the local entry is kept unchanged and the name is reported in mcp_skipped. If the local entry has no credentials, it's replaced as before.
  5. Stale session id: cleared when a renewed initialize returns no Mcp-Session-Id.

Also, adding a server (/mcp add, Add from JSON) now refuses to save over a config file that can't be read (the _add_entry part of your #542 note).

Tests: each fix has a regression test that fails on the previous commit. The MCP tests give 220 passed, 8 skipped, and the full suite gives 5095 passed, with only the known dev failures.

@ahmad-ajmal ahmad-ajmal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for the quick turnaround on the first round. I've read all the production changes against dev. Overall this is in good shape: the design is sound and the tests are thorough. There's one fix I'd like before merging, plus some cleanup.

The approach

  • Writing the transport directly on httpx instead of using the official MCP SDK is the right call for us. The SDK (2.3.0) pulls in server-side packages a client doesn't need (starlette, uvicorn, sse-starlette, pydantic, pyjwt, opentelemetry). Our other transports are hand-written on httpx too.
  • The security choices are good:
    • ${NAME} only reads the server's own env.
    • Redirects aren't followed.
    • Header values are validated and never logged.
  • The cost is ~700 lines of protocol code we maintain ourselves. If we add OAuth later, let's look at the SDK again before writing that by hand.

Please fix before merging

  1. Tool calls can be 1 second slower than they need to be (_drain, inline comment).
  2. Remove the now-unused unregister_mcp_tools, and merge the duplicated helpers (inline comments).

OK as follow-ups

  • If session renewal fails, the server stays offline until the config changes or the app restarts (inline).
  • The web UI doesn't know about invalid entries yet. They look like normal servers, and toggling one shows a "not found" error.
  • Header values are hidden from the UI, but env values are still sent to the browser (mcp_list, mcp_get_env). That's where the ${NAME} secret actually lives. This was already true before this PR; I assume the UI PR fixes it.
  • The old SSE transport still can't send headers.
  • Not part of this PR: httpx-sse is in requirements.txt but nothing imports it, so we could drop it.

What I tested
On macOS, Python 3.10, with the locked httpx 0.28.1, I ran test_mcp_streamable_http.py, test_mcp_config.py and test_mcp_sse_transport.py: 126 passed. I stubbed out the app's heavy imports so these modules load on their own. I didn't run the lifecycle and settings tests locally.

chunks.append(chunk)
return b"".join(chunks)

async def _drain(self, iterator) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tool calls can wait an extra second after they already have their answer.

When the server answers as an SSE stream, _drain keeps reading after the response has arrived. It stops when the server closes the stream or when DRAIN_TIMEOUT (1 s) runs out. Servers should close the stream after the response, but the spec doesn't require it. With a server that leaves it open, every tool call waits the full second.

I measured this against a small test server that keeps the stream open: about 1 s per tools/list, against about 1 ms with the change below.

I understand why it's there. If we stop reading halfway, the garbage collector later closes httpx's generator chain from another task, and anyio raises "exit cancel scope in a different task". Closing the iterator ourselves does the same cleanup right away, in this task, without waiting:

async def _drain(self, iterator) -> None:
    """Close an httpx stream iterator now, in this task, so its generator
    chain isn't left for the garbage collector to close from another task."""
    try:
        await iterator.aclose()
    except Exception:  # noqa: BLE001 — the stream is being discarded
        pass

With this change the 126 transport, config and SSE tests still pass on httpx 0.28.1 / httpcore 1.0.9, with no event-loop errors or unraisable-exception warnings.

The same applies to _read_limited (line 1285). Once a body is over the limit, it currently keeps downloading it for up to another second just to throw it away. Closing stops that immediately. With this change, _close_stream might be a better name.

try:
await self._renew_session(expired)
except _HTTPTransportError as e:
self._connected = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If renewing the session fails, the server stays offline until the config changes or the app restarts.

This line marks the connection as closed. After that, MCPClient.call_tool answers "connection lost" for every call to this server, and nothing tries to reconnect. reload() does retry dead servers, but it only runs when mcp_config.json changes. So if the server is briefly unavailable while it restarts, its tools stay broken until someone edits the config or restarts CraftBot.

Two possible fixes:

  • have the next call try one reconnect for http servers;
  • or leave _connected as it is here, so the next request tries the renewal again.

Fine as a follow-up.

return f"mcp_{server_name}_{tool_name}"

@staticmethod
def unregister_actions(action_names) -> int:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unregister_mcp_tools (line 308) is now unused.

This new method replaces it, and nothing calls the old one any more. The old one still has the bug this docstring describes: removing server "foo" also removes "foo_bar"'s tools. Could you delete it so nobody uses it again by mistake?

return False


def _missing_config(server: MCPServerConfig) -> List[str]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same "which env keys are missing?" check is written in several places.

_missing_config here and the env part of _mcp_needs_config in profile_bundle.py (line 152) do the same thing, one on a config object and one on a dict. If they ever drift apart, /mcp list and the bundle importer will report different missing keys for the same server. Could it be one method on MCPServerConfig, for example missing_env_keys()?

The web UI has a third version (MCPSettings.tsx:149). It only looks at env, so it misses keys referenced from headers. In the UI PR it could use needs_config from this payload instead.

await self._drain(chunks)
return outcome

async def _sse_messages(self, lines, outcome: "_StreamOutcome"):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are now two SSE parsers.

This parses SSE events, and SSETransport has its own parser for the same format (around line 591). They already share the line splitter, _sse_lines. Could they share the event parsing too, for example one generator that yields event, data, id and retry?

The line-separator bug from the first round was in both copies, so one shared parser means a fix only has to happen once.

return MCPConfig()


def _load_for_update() -> Tuple[Optional[MCPConfig], str]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the config file is broken, most commands give a misleading error.

Only adding a server uses this loader. Remove, enable, disable, env and header still use load_mcp_config(), which returns an empty config when the file can't be read. They don't damage anything, since they stop when the server isn't found. But the user sees "Server 'x' not found" when the real problem is that the file is broken. Could all the commands that change the file use this loader?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants